/**
    package: learn-go
    filename: channel
    author: diogo@gmail.com
    time: 2021/9/15 16:47
**/
package main

import (
	"fmt"
	"runtime"
	"time"
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU()) // 其实这里可以不用特意写，默认会取系统CPU最多时
	c := make(chan bool, 100)
	t := time.Tick(time.Second) // 一秒的心跳

	go func() {
		for {
			select {
			case <-t:
				watching() // 一秒打印当前goroutine运行个数
			}
		}
	}()

	for i := 0; i < 1000; i++ {
		c <- true // c 只能缓存100个
		go worker(i, c)
	}

	fmt.Println("Done")
}

func watching() {
	fmt.Printf("NumGoroutine: %d\n", runtime.NumGoroutine())
}

func worker(i int, c chan bool) {
	fmt.Println("worker", i)
	time.Sleep(2 * time.Second) // 模拟其他代码运行消耗时间
	<-c
}
